<template>
  <view class="w100p common_wrap no-bg">
    <CommonHeader :title="typeTranslate == 1 ? '发布线下翻译需求' : '发布问询服务'"></CommonHeader>

    <view class="w100p pr list_block">
      <scroll-view scroll-y>
        <!-- 标题 -->
        <view class="box-same">
          <view class="inp-li">
            <view class="title">{{$t('标题')}}<text>*</text></view>
            <view class="inp">
              <input type="text" :placeholder="$t('请输入标题')" placeholder-class="input-placeholder-cai"
                v-model="paramsSubmit.title" maxlength="100"/>
            </view>
          </view>
        </view>
        <view class="box-same">
          <view class="inp-li" @click="isShowUnit = true">
            <view class="title">{{$t('发布类型')}}<text>*</text></view>
            <view class="inp">
              <view :class="{ txt: true, 'active': currentItemType.title }">{{ currentItemType.title || $t('请选择发布类型') }}
              </view>
              <view class="aroow">
                <image src="/static/caigou/xiala.png" />
              </view>
            </view>
          </view>

        </view>
        <!-- 采购简介 -->
        <view class="box-same caigou-jianjie">
          <view class="title">{{$t('内容详情')}}<text class="require">*</text></view>
          <view class="textarea">
            <textarea placeholder="请输入内容详情*" placeholder-class="input-placeholder-cai"
              v-model="paramsSubmit.content" maxlength="240"></textarea>
            <!-- <view class="num">5/200</view> -->
          </view>
        </view>
        <!-- 图片上传 -->
        <view class="box-same upload-wrapper">
          <view class="upload-li">
            <view class="title">{{$t('上传图片')}}<text class="require">*</text><text class="yaoqiu">{{$t('支持')}}jpeg、jpg、png (大小5m内)</text>
            </view>
            <view class="uploads">
              <view class="img" v-for="(item, index) in imgList" :key="index" @click="onPreview(item.fullurl)">
                <image :src="item.fullurl" mode="aspectFill" />
                <view class="delete" @click.stop="onDelete(index, 'imgList')">
                  <uni-icons type="closeempty" color="#fff" size="12" />

                </view>
              </view>
              <view class="img" @click="onUpload({type: 'image',size: 5,count: 3})" v-if="imgList.length < 3">
                <image src="/static/caigou/upload.png" />
              </view>
            </view>
          </view>
          <view class="upload-li">
            <view class="title">{{$t('上传视频')}}<text class="yaoqiu">{{$t('支持')}}mp4、rmvb、AVI (大小500m内)</text></view>
            <view class="uploads">
              <view class="img zhan" v-for="(item,index) in videoList" :key="index" @click="onPreviewVideo(item.fullurl)">
                <image src="" mode="aspectFill" style="background-color: azure;"/>
								<image src="/static/icon/play.png" mode="aspectFill" class="paly"></image>
                <view class="delete" @click.stop="onDelete(index, 'videoList')">
                  <uni-icons type="closeempty" color="#fff" size="12" />
                </view>
              </view>
              <view class="img"  @click="onUpload({type: 'video',size: 500,count: 1})"  v-if="videoList.length < 1">
                <image src="/static/caigou/upload.png" />
              </view>
            </view>
          </view>
        </view>
        <view class="box-same">
          <view class="inp-li" @click="isJifen = true">
            <view class="title">
              {{$t('信息价格（积分')}}）<text>*</text>
              <view class="fali">{{$t('平台返利')}}</view>
            </view>
            <view class="inp">
              <view :class="{ txt: true, 'active': paramsSubmit.score }">{{ paramsSubmit.score ? paramsSubmit.score :
                $t('信息价格（积分）') }}</view>
              <view class="aroow">
                <image src="/static/caigou/xiala.png" />
              </view>
            </view>
          </view>

        </view>


        <view style="height: 16rpx;"></view>
      </scroll-view>
    </view>

    <!-- 取消 -->
    <view class="btn-wrap" >
      <view class="btn green" @click="submit">{{$t('发布')}}</view>
    </view>



    <!-- 类型 -->
    <view v-if="isShowUnit">

      <u-popup :show="isShowUnit" @close="onClose" round="34">
        <view class="pop-wrapper">
          <view class="headerxx">
            <image src="/static/caigou/chacha.png" @click="onClose" />
          </view>
          <view class="scroll-w">
            <scroll-view scroll-y>
              <view class="lists">
                <view :class="{ list: true, 'active': index === currentIndex }" v-for="(item, index) in listUnits"
                  :key="index" @click="onChangeTapClass(index)">
                  {{ item.title }}
                </view>
              </view>
            </scroll-view>
          </view>

          <view class="btn" @click="confirmUnit">{{$t('确定')}}</view>
        </view>
      </u-popup>
    </view>

    <!-- 积分 -->
    <view v-if="isJifen">

      <u-popup :show="isJifen" @close="onClose" round="34">
        <view class="pop-wrapper">
          <view class="headerxx">
            <image src="/static/caigou/chacha.png" @click="onClose" />
          </view>
          <view class="scroll-w">
            <scroll-view scroll-y>
              <view class="lists">
                <view :class="{ list: true, 'active': index === currentIndexJifen }" v-for="(item, index) in jifenList"
                  :key="index" @click="onChangeTapJifen(index)">
                  {{ item }}
                </view>
              </view>
            </scroll-view>
          </view>

          <view class="btn" @click="confirmJifen">{{$t('确定')}}</view>
        </view>
      </u-popup>
    </view>



    		<!-- 播放视频 -->
		<uni-popup ref="popupVideo" type="center" background-color="#000" mask-background-color="#000" class="popvexxx">
			<view class="wrapper-video">
				<video  :src="previewVideoUrl" :show-center-play-btn="true" object-fit="cover"
					play-btn-position="center" :controls="true" :autoplay="true" class="video-main">
				</video>
			</view>
		</uni-popup>

  </view>
</template>


<script>
import { cate_list,state_add,state_info,state_update,score_select } from '@/api/state.js';
import { uploadFile, chooseFile } from '@/utils/tool.js';

let lock = true;

import CommonHeader from "@/pages/translate/components/common-header.vue";
export default {
  components: {
    CommonHeader
  },
  data() {
    return {
      listUnits: [],
      jifenList: [],
      currentIndex: null,
      isShowUnit: false,
      isJifen: false,
      currentItemType: {}, // 发布类型

      currentIndexJifen: null, // 积分索引
      currentItemJifen: {}, // 发布类型

      // 参数提交
      paramsSubmit: {
        user_id: uni.getStorageSync('user_id'),
        cate_id: '',
        score: '',
        title: '',
        content: '',
        image: '',
        video: '',
      },
      imgList: [],
      videoList: [], // 视频
      previewVideoUrl: '',
      goods_id: '',
      typeTranslate: 0, // 0 线上 1 线下

    }
  },
  onLoad(options) {
    this.goods_id = options.id;
    this.typeTranslate = options.typeTranslate;
    this.getData();
    this.getPoint();
  },
  methods: {
    getPoint() {
      score_select({

      }).then((res) => {
        this.jifenList = res.data.data.data;
      })
    },
    // 数据回填
    getDetail() {
      state_info({
        id: this.goods_id,
        user_id: uni.getStorageSync('user_id')
      }).then((res) => {
        let info = res.data.data.data;
        // 发布类型回填
        this.paramsSubmit.cate_id = info.cate_id;
        let index = this.listUnits.findIndex((ele)=> {
          return ele.id == info.cate_id
        })
        index = index > -1 ? index : 0;
        this.currentItemType = this.listUnits[index] || {};
        this.currentIndex = index;
        
        this.paramsSubmit.title = info.title;
        this.paramsSubmit.content = info.content;
        // 图片
        let arrImg = [];
        let arrPic = [];
        info.image.forEach((ele)=> {
          arrImg.push({
            url: this.getImageUrl(ele.path),
            fullurl: this.getImageUrl(ele.path),
          })
          arrPic.push(this.getImageUrl(ele.path))
        })

        this.imgList = arrImg;

        this.paramsSubmit.image = arrPic.join(',')
         // 视频
        let arrVideo = [];
        let arrMp = [];
        info.video.forEach((ele)=> {
          arrVideo.push({
            url: this.getImageUrl(ele.path),
            fullurl: this.getImageUrl(ele.path),
          })
          arrMp.push(this.getImageUrl(ele.path))
        })

        this.videoList = arrVideo;
        this.paramsSubmit.video = arrMp.join(',');

        // 积分
        this.paramsSubmit.score = info.score;
        let idx = this.jifenList.findIndex((ele)=> {
          return ele == info.score;
        })
        this.currentIndexJifen = idx;
        this.currentItemJifen = this.jifenList[idx]

      })
    },
    // 预览视频
    onPreviewVideo(url) {
      this.previewVideoUrl = url;
      this.$refs.popupVideo.open()
    },
    // 删除图片
    onDelete(index, arr) {
      this[arr].splice(index, 1)
    },
    // 上传视频和图片
    async onUpload({type,size,count}) {
      let res = await uploadFile(await chooseFile({
        type,
        size,
        count,
      }))
      console.log(type,'------',res)
      if (type == 'image') {
        this.imgList.push(res);
      }
      if (type == 'video') {
        this.videoList.push(res);
      }

    },
    onPreview(current) {
      uni.previewImage({
        current,
        urls: [current]
      })
    },

    // 获取数据
    getData() {
      cate_list({
        type: this.typeTranslate,
      }).then((res) => {
        this.listUnits = res.data.data.data;
        if (this.goods_id) {
          this.getDetail();
        }
      })
    },
    onChangeTapClass(index) {
      this.currentIndex = index;
    },
    onChangeTapJifen(index) {
      this.currentIndexJifen = index;
    },
    onClose() {
      this.isShowUnit = false;
      this.isJifen = false
    },
    confirmUnit() {
      if (this.currentIndex === null) {
        uni.showToast({
          title: this.$t('请选择发布类型'),
          icon: 'none',
        })
        return;
      }
      this.isShowUnit = false;
      this.currentItemType = this.listUnits[this.currentIndex]
      this.paramsSubmit.cate_id = this.currentItemType.id;
    },
    confirmJifen() {
      if (this.currentIndexJifen === null) {
        uni.showToast({
          title: this.$t('请选择积分'),
          icon: 'none',
        })
        return;
      }
      this.isJifen = false;
      this.currentItemJifen = this.jifenList[this.currentIndexJifen]
      this.paramsSubmit.score = this.currentItemJifen
    },

    async submit() {
      if (!this.paramsSubmit.title) {
        uni.showToast({
          title: this.$t('请输入标题'),
          icon: 'none',
        })
        return;
      }
      if (!this.paramsSubmit.cate_id) {
        uni.showToast({
          title: this.$t('请选择发布类型'),
          icon: 'none',
        })
        return;
      }
      if (!this.paramsSubmit.content) {
        uni.showToast({
          title: this.$t('请输入内容详情'),
          icon: 'none',
        })
        return;
      }

      if (!this.imgList.length) {
        uni.showToast({
          title: this.$t('请上传图片'),
          icon: 'none',
        })
        return;
      }

    

      if (!this.paramsSubmit.score) {
        uni.showToast({
          title: this.$t('请选择积分'),
          icon: 'none',
        })
        return;
      }
      if (!lock) {
        return;
      }
      lock = false;

      let arrImg = [];
      this.imgList.forEach((ele)=> {
        arrImg.push(ele.url)
      })

      let arrVideo = [];
      this.videoList.forEach((ele)=> {
        arrVideo.push(ele.url)
      })

      uni.showLoading({ title: 'loading...', mask: true, })
      let api = this.goods_id ? state_update : state_add;
      try {
        let res = await api({
          ...this.paramsSubmit,
          image: arrImg.join(','),
          video: arrVideo.join(','),
          id: this.goods_id || 0,
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: this.$t('提交成功'),
          })
          setTimeout(() => {
            uni.hideLoading({})
            uni.navigateBack({})
            setTimeout(() => {
              lock = true;
            }, 700);
          }, 700);
        } else {
          uni.hideLoading({})
          lock = true;
        }

      } catch (error) {
        uni.hideLoading({})
        lock = true;
      }



    }
  },
}

</script>



<style lang="scss" scoped>
@import '@/pages/translate/common/common.scss';
@import './index.scss';
</style>


<style>
.input-placeholder-cai {
  color: #606366;
  font-size: 26rpx;
}
</style>